package com.glory.brepda.activity.mfg;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.GroupEqpListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.EqpStatusEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.entity.stateChangeEntity;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.OnClick;

public class eqpStateChangeActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.etEqpId)
    FreeUI_ClearEditText etEqpId;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.teEqpStatu)
    TextView teEqpStatu;
    @BindView(R.id.teChangeStateTime)
    TextView teChangeStateTime;
    @BindView(R.id.teLotId)
    TextView teLotId;
    @BindView(R.id.teDuration)
    TextView teDuration;
    @BindView(R.id.flStateList)
    FrameLayout flStateList;
    @BindView(R.id.ivStateArrow)
    ImageView ivStateArrow;
    @BindView(R.id.tvState)
    TextView tvState;
    @BindView(R.id.flParentStateList)
    FrameLayout flParentStateList;
    @BindView(R.id.ivParentStateArrow)
    ImageView ivParentStateArrow;
    @BindView(R.id.tvParentState)
    TextView tvParentState;


    private GroupEqpListAdapter myAdapter;


    private Set<String> parentStateSet = new HashSet<>();

    private Map<String,stateChangeEntity.RasEqpStateEntity> stateMap = new HashMap<>();

    private FreeUI_GeneralPop statePop;
    private FreeUI_GeneralPop parentStatePop;

    private boolean repairCompleteFlag=false;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_eqp_state_change;
    }

    @Override
    protected void initView() {
        setMainLayout(llMain);
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        tvBaseSubmit.setText("提交");
        myAdapter = new GroupEqpListAdapter(null,false);
        myAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        myAdapter.isFirstOnly(true);
        tvParentState.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // 在文本改变后调用
                if (!stateMap.isEmpty() && !tvParentState.getText().toString().equals("")){
                    tvState.setText(filterStateList(tvParentState.getText().toString()).get(0));
                }


            }
        });
    }

    @Override
    protected void initData() {
        initEdit(etEqpId, this::requestStateList);
    }

    @OnClick({R.id.flParentStateList,R.id.flStateList,R.id.tvBaseSubmit})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.flStateList) {
//            if (statePop != null) {
//                if (statePop.isShowing()) {
//                    statePop.dismiss();
//                }
//            } else {
//                /**stateList.stream()
//                 .filter(state -> state.getState() == tvParentState.getText())
//                 .collect(Collectors.toList())**/
//                statePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flStateList.getWidth(),filterStateList(tvParentState.getText().toString()), ivStateArrow, (codeS, i) -> {
//                    tvState.setText(codeS);
//                });
//            }
            /**stateList.stream()
             .filter(state -> state.getState() == tvParentState.getText())
             .collect(Collectors.toList())**/
            statePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flStateList.getWidth(),filterStateList(tvParentState.getText().toString()), ivStateArrow, (codeS, i) -> {
                tvState.setText(codeS);
            });
            FreeApi_PopUtils.setArrowShow(ivStateArrow);
            statePop.showAsDropDown(flStateList, 0, 0);
        }else if (view.getId() == R.id.tvBaseSubmit) {
            if ("".equals(getText(etEqpId))){
                showToast("设备号不能为空", false);
                return;
            }
            if ("".equals(tvState.getText()) || "".equals(tvParentState.getText())){
                showToast("目标状态不能为空", false);
                return;
            }
            if(StringUtils.isNotBlank(teEqpStatu.getText())){
                if (stateMap.get(teEqpStatu.getText()).getCode().startsWith("2-") && repairCompleteFlag){
                    showToast("设备"+getText(etEqpId)+"还有修机任务未完成，不允许转状态",false);
                    return;
                }
            }

            submitChange();
        }else if (view.getId() == R.id.flParentStateList) {

            parentStatePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flParentStateList.getWidth(), new ArrayList<>(parentStateSet), ivParentStateArrow, (codeS, i) -> {
                tvParentState.setText(codeS);
            });
            FreeApi_PopUtils.setArrowShow(ivParentStateArrow);
            parentStatePop.showAsDropDown(flParentStateList, 0, 0);
        }

    }

    private void checkRepairState(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<JsonObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JsonObject>>
                (new TypeToken<BaseResponseBean<JsonObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JsonObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    JsonObject jsonObject = response.body().getResponse().getBody();
                    repairCompleteFlag="Y".equals(jsonObject.get("WORKSTATE").getAsString())?true:false;
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JsonObject>> response) {
                super.onError(response);
                loadError(response.getException(),"BREEQUCALLOUTMAINTAIN");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",eqpID);
        map.addProperty("ACTIONTYPE","CHECKSTATE");
        NetUtils.requestPostNet("IF.BREEQUCALLOUTMAINTAIN","Common", eqpStateChangeActivity.this,map,callBack);
    }

    private void generateQcRequest(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<stateChangeEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<stateChangeEntity>>
                (new TypeToken<BaseResponseBean<stateChangeEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<stateChangeEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<stateChangeEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("JOB_TYPE",stateMap.get(tvParentState.getText()+"-"+tvState.getText()).getTriggerTiming());
        map.addProperty("LOT_ID","null".equals(teLotId.getText().toString())?"":teLotId.getText().toString());
        List<String> eqpList = new ArrayList<>();
        eqpList.add(eqpID);
        map.add("EQUIPMENT",new JsonParser().parse(new Gson().toJson(eqpList)).getAsJsonArray());
        NetUtils.requestPostNet("IF.GENERATECPCQCFORM","Common", eqpStateChangeActivity.this,map,callBack);
    }

    private List<String> filterStateList(String parentState) {
        List<String> result = new ArrayList<>();
//        for (int i = 0; i < stateMap.values().size(); i++) {
//            if (stateMap.values().get(i).getState().equals(parentState)){
//                result.add(stateList.get(i).getSubState());
//            }
//        }
        for (stateChangeEntity.RasEqpStateEntity state: stateMap.values()) {
            if(state.getState().equals(parentState)){
                result.add(state.getSubState());
            }
        }
        return result;
    }

    private void requestStateList(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<stateChangeEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<stateChangeEntity>>
                (new TypeToken<BaseResponseBean<stateChangeEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<stateChangeEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<stateChangeEntity.RasEqpStateEntity> tempStateList = response.body().getResponse().getBody().getStateList();
                    for (stateChangeEntity.RasEqpStateEntity state : tempStateList) {
                        parentStateSet.add(state.getState());
                        stateMap.put(state.getState() + "-" + state.getSubState(),state);
                        teEqpStatu.setText(response.body().getResponse().getBody().getSpecialState()==null?"":response.body().getResponse().getBody().getSpecialState());
                        teChangeStateTime.setText(response.body().getResponse().getBody().getSTATE_CHANGE_TIME());
                        teDuration.setText(response.body().getResponse().getBody().getDURATION());
                        teLotId.setText("".equals(response.body().getResponse().getBody().getLOTID())?"null":response.body().getResponse().getBody().getLOTID());
                    }
                }
                tvParentState.setText("");
                tvState.setText("");
                checkRepairState(getText(etEqpId));
            }

            @Override
            public void onError(Response<BaseResponseBean<stateChangeEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","GETSTATUS");
        map.addProperty("EQUIPMENTID",eqpID);
        parentStateSet.clear();
        stateMap.clear();
        teEqpStatu.setText("");
        teChangeStateTime.setText("");
        teDuration.setText("");
        NetUtils.requestPostNet("IF.BRECHANGESTATE","Common", eqpStateChangeActivity.this,map,callBack);
    }

    private void submitChange() {
        FreeUI_DialogEntityCallBack<BaseResponseBean<stateChangeEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<stateChangeEntity>>
                (new TypeToken<BaseResponseBean<stateChangeEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<stateChangeEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    String key =tvParentState.getText()+"-"+tvState.getText();
                    if (!stateMap.get(key).getCode().startsWith("2-") && !"null".equals(teLotId.getText())){
                        if (!"".equals(stateMap.get(tvParentState.getText()+"-"+tvState.getText()).getTriggerTiming())
                        && stateMap.get(tvParentState.getText()+"-"+tvState.getText()).getTriggerTiming() !=null){
                            generateQcRequest(getText(etEqpId));
                        }
                    }
                    if(tvParentState.getText().toString().equals("正常作业") && tvState.getText().toString().equals("作业中")){
                        checkInfo(getText(etEqpId));
                    }else {
                        showToast("修改成功！", true);
//                    teEqpStatu.setText(tvParentState.getText()+"-"+tvState.getText());
                        requestStateList(getText(etEqpId));
                    }


                }
            }

            @Override
            public void onError(Response<BaseResponseBean<stateChangeEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","CHANGE");
        map.addProperty("EQUIPMENTID",getText(etEqpId));
        map.addProperty("TARGETSTATE",stateMap.get(tvParentState.getText()+"-"+tvState.getText()).getCode());


        NetUtils.requestPostNet("IF.BRECHANGESTATE","Common", eqpStateChangeActivity.this,map,callBack);
    }

    private void checkInfo(String eqpID){

        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    showToast("修改成功！", true);
//                    teEqpStatu.setText(tvParentState.getText()+"-"+tvState.getText());
                    requestStateList(eqpID);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(),"EQPSHIFTSTATUS");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",getText(etEqpId));
        map.addProperty("EQUIPMENTSTATUS",teEqpStatu.getText().toString());
        map.addProperty("WAITTIME",teChangeStateTime.getText().toString());
        NetUtils.requestPostNet("IF.EQPSHIFTSTATUS","Common",eqpStateChangeActivity.this,map,callBack);

    }


}
